<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class session_db implements session_interface {

	protected $table = '';
	protected $db = null;

	public function __construct($save_path) {

		$this->table = (!empty($save_path)) ? $save_path : 'core_sessions';
		$this->db = db::instance();

	}

	public function read($id) {

		$r = $this->db->_row(sprintf("SELECT * FROM %s WHERE session_id = '%s';", $this->table, $this->db->escape_string($id)));

		if(!empty($r)) {
			// it returns false on fail
			$r['user_data'] = $this->unserialize($r['user_data']);

			return $r;
		}

		return false;
	}

	public function write($data) {

		if(is_array($data) && isset($data['user_data'])) {
			$data['user_data'] = $this->serialize($data['user_data']);
		} else
			return false;

		$str = $this->db->make_set_list($data);

		$r = $this->db->exec(
				sprintf("UPDATE %s SET %s WHERE session_id='%s';", $this->table, $str,
						$this->db->escape_string($data['session_id'])
					)
				);

		return !empty($r);
	}

	public function create($data) {

		if(is_array($data) && isset($data['user_data']))
			$data['user_data'] = $this->serialize($data['user_data']);
		else
			return false;

		$data = $this->db->make_set_list($data);

		$r = $this->db->exec(sprintf("INSERT INTO %s SET %s;", $this->table, $data));

		return !empty($r);
	}

	public function destroy($id) {

		$r = $this->db->exec(sprintf("DELETE FROM %s WHERE session_id='%s';", $this->table, $this->db->escape_string($id)));

		return !empty($r);
	}

	public function gc($expire) {
		$r = $this->db->exec(sprintf("DELETE FROM %s WHERE last_activity < %d;", $this->table, $expire));

		return $r;
	}

	protected function serialize($data) {
		return serialize($data);
	}

	protected function unserialize($data) {
		return unserialize($data);
	}

}
